package com.saic.utils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.saic.produce.OracleProduce;


/**
 * 
 * @author hongliang.dinghl Dom4j 生成XML文档与解析XML文档
 */
public class Dom4j {
    public static void main(String[] args){
    	//createXml( "conf/tableInfo.xml");
    	parserXml("conf/tableInfo.xml");
    }
	public static void createXml(String fileName) {
		Document document = DocumentHelper.createDocument();
		Element tableInfos = document.addElement("tableInfos");
		
		Element tableInfo = tableInfos.addElement("tableInfo");
		Element tableName = tableInfo.addElement("tableName");
		Element rowkey = tableInfo.addElement("rowkey");
		tableName.setText("T_VIN_VEHICLE_USE_MAPPING");
		rowkey.setText("VIN");
		
		/*tableName.setText("T_VIN_VEHICLE_USE_MAPPING");
		rowkey.setText("VIN");*/
		
		try {
			Writer fileWriter = new FileWriter(fileName);
			XMLWriter xmlWriter = new XMLWriter(fileWriter);
			xmlWriter.write(document);
			xmlWriter.close();
		} catch (IOException e) {

			System.out.println(e.getMessage());
		}

	}

	public static Map<String,String> parserXml(String fileName) {
		Map<String,String> tableInfo = new HashMap<String, String>();
		File inputXml = new File(fileName);
		SAXReader saxReader = new SAXReader();
		try {
			Document document = saxReader.read(inputXml);
			Element employees = document.getRootElement();
			for (Iterator i = employees.elementIterator(); i.hasNext();) {
				Element employee = (Element) i.next();
				StringBuffer tableName = new StringBuffer();
				StringBuffer rowKey = new StringBuffer();
				int count = 0;
				for (Iterator j = employee.elementIterator(); j.hasNext();) {
					Element node = (Element) j.next();
					if((++count ) %2 == 0){
						rowKey.append(node.getText());
					}
					else{
						tableName.append(node.getText());
					}
					System.out.println(node.getName() + ":" + node.getText());
				}
				tableInfo.put(tableName.toString(),rowKey.toString());
				tableName.deleteCharAt(0);
				rowKey.deleteCharAt(0);
			}
		} catch (DocumentException e) {
			System.out.println(e.getMessage());
		}
		return tableInfo;
		//System.out.println("dom4j parserXml");
	}
}
